// static/js/user_mgmt.js

// 全局变量，保存当前列表数据
let usersData = [];

// 当前操作的用户 ID
let currentResetUserId = null;
let currentEditUserId  = null;
let currentDeleteUserId = null;

// 初始化 Bootstrap Modal 实例
const addUserModalEl   = document.getElementById('addUserModal');
const addUserModal     = new bootstrap.Modal(addUserModalEl);
const addUserForm      = document.getElementById('add-user-form');

const resetPwdModalEl  = document.getElementById('resetPwdModal');
const resetPwdModal    = new bootstrap.Modal(resetPwdModalEl);
const resetPwdForm     = document.getElementById('reset-pwd-form');

const editUserModalEl  = document.getElementById('editUserModal');
const editUserModal    = new bootstrap.Modal(editUserModalEl);
const editUserForm     = document.getElementById('edit-user-form');

const confirmDeleteModalEl = document.getElementById('confirmDeleteModal');
const confirmDeleteModal   = new bootstrap.Modal(confirmDeleteModalEl);
const deleteConfirmBtn     = document.getElementById('delete-confirm-btn');

const userMgmtMsgEl = document.getElementById('userMgmtMsg');

const userSearchInput = document.getElementById('userSearch');


function renderUserList(list) {
  const tbody = document.querySelector('#user-table tbody');
  tbody.innerHTML = '';
  list.forEach(u => {
    const tr = document.createElement('tr');
    if (!u.is_active) tr.classList.add('table-danger');
    tr.innerHTML = `
      <td>${u.username}</td>
      <td>${u.is_active ? '是' : '否'}</td>
      <td class="text-center">
        <!-- 重置密码：信息风格 -->
        <button class="btn btn-sm btn-outline-info me-1" title="重置密码" onclick="resetPwd(${u.id})">
          <i class="bi bi-key-fill"></i>
        </button>
        <!-- 编辑用户：成功风格 -->
        <button class="btn btn-sm btn-outline-success me-1" title="编辑用户" onclick="editUser(${u.id})">
          <i class="bi bi-pencil-fill"></i>
        </button>
        <!-- 删除用户：警告风格 -->
        <button class="btn btn-sm btn-outline-warning" title="删除用户" onclick="deleteUser(${u.id})">
          <i class="bi bi-trash-fill"></i>
        </button>
      </td>
    `;
    tbody.appendChild(tr);
  });
}
// ---------------------------------------
// 1. 加载并渲染用户列表
// ---------------------------------------
async function loadUserList() {
  try {
    const res = await fetch('/api/users');
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    usersData = await res.json();
    renderUserList(usersData);

    const tbody = document.querySelector('#user-table tbody');
    tbody.innerHTML = '';

    usersData.forEach(u => {
      const tr = document.createElement('tr');
      if (!u.is_active) tr.classList.add('table-danger');

      tr.innerHTML = `
        <td>${u.username}</td>
        <td>${u.is_active ? '是' : '否'}</td>
        <td class="text-center">
          <button class="btn btn-sm btn-outline-info me-1" title="重置密码" onclick="resetPwd(${u.id})">
            <i class="bi bi-key-fill"></i>
          </button>
          <button class="btn btn-sm btn-outline-success me-1" title="编辑用户" onclick="editUser(${u.id})">
            <i class="bi bi-pencil-fill"></i>
          </button>
          <button class="btn btn-sm btn-outline-warning" title="删除用户" onclick="deleteUser(${u.id})">
            <i class="bi bi-trash-fill"></i>
          </button>
        </td>
      `;
      tbody.appendChild(tr);
    });
  } catch (err) {
    console.error('Failed to fetch users:', err);
    alert('加载用户列表失败：' + err.message);
  }
}

// 实时搜索：监听 input 事件
userSearchInput.addEventListener('input', () => {
  const kw = userSearchInput.value.trim().toLowerCase();
  if (!kw) {
    renderUserList(usersData);
  } else {
    // 同时匹配用户名或真实姓名
    const filtered = usersData.filter(u =>
      u.username.toLowerCase().includes(kw) ||
      (u.full_name && u.full_name.toLowerCase().includes(kw))
    );
    renderUserList(filtered);
  }
});

// 页面加载完成后，先加载列表，再自动 focus 搜索框
document.addEventListener('DOMContentLoaded', () => {
  loadUserList().then(() => userSearchInput.focus());
});

// ---------------------------------------
// 2. 添加用户
// ---------------------------------------
// 打开添加用户弹框时重置表单
document.getElementById('add-user-btn').addEventListener('click', () => {
  addUserForm.reset();
  // 清除错误消息
  const errEl = document.getElementById('addUserError');
  errEl.style.display = 'none';
  errEl.textContent = '';
  addUserModal.show();
});

// 提交添加用户表单
addUserForm.addEventListener('submit', async e => {
  e.preventDefault();
  const errEl = document.getElementById('addUserError');
  errEl.style.display = 'none';
  errEl.textContent = '';

  const data = {
    username:    addUserForm.username.value.trim(),
    full_name:   addUserForm.full_name.value.trim(),
    password:    addUserForm.password.value,
    expiry_date: addUserForm.expiry_date.value,
    is_admin:    addUserForm.is_admin.checked,
    remarks:     addUserForm.remarks.value.trim()
  };

  try {
    const res = await fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });

    // 先读取原始文本，再尝试解析 JSON
    const text = await res.text();
    let payload;
    try {
      payload = JSON.parse(text);
    } catch {
      throw new Error('服务器返回非 JSON 内容');
    }

    // 如果状态码不是 2xx，就显示后端的 error 或 message
    if (!res.ok) {
      const msg = payload.error || payload.message || `状态码 ${res.status}`;
      errEl.textContent = msg;
      errEl.style.display = 'inline';
      setTimeout(() => { errEl.style.display = 'none'; }, 3000);
      return;
    }

    // 成功：隐藏弹框并刷新列表
    addUserModal.hide();
    await loadUserList();

  } catch (err) {
    // 捕获网络或解析等意外错误
    errEl.textContent = err.message;
    errEl.style.display = 'inline';
    setTimeout(() => { errEl.style.display = 'none'; }, 3000);
    console.error('Add user error:', err);
  }
});

// ---------------------------------------
// 3. 重置密码功能
// ---------------------------------------
function resetPwd(userId) {
  currentResetUserId = userId;
  resetPwdForm.reset();
  resetPwdModal.show();
}

resetPwdForm.addEventListener('submit', async e => {
  e.preventDefault();
  const newPwd = resetPwdForm['new_password'].value.trim();
  if (!newPwd) return;

  try {
    const res = await fetch(`/api/users/${currentResetUserId}/reset_password`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ new_password: newPwd })
    });
    const text = await res.text();
    let payload;
    try { payload = JSON.parse(text); } catch { throw new Error(text); }
    if (!res.ok) throw new Error(payload.error || payload.message || text);

    // 隐藏重置密码 Modal
    resetPwdModal.hide();

    // 在“用户管理” Modal 头部显示成功提示
    userMgmtMsgEl.textContent = '密码重置成功';
    userMgmtMsgEl.style.display = 'inline';
    // 3 秒后隐藏提示
    setTimeout(() => { userMgmtMsgEl.style.display = 'none'; }, 3000);

  } catch (err) {
    alert('重置失败：' + err.message);
    console.error('Reset password error:', err);
  }
});
// ---------------------------------------
// 4. 编辑用户功能
// ---------------------------------------
function editUser(userId) {
  currentEditUserId = userId;
  const user = usersData.find(u => u.id === userId);
  if (!user) return alert('找不到该用户数据');

  editUserForm.reset();
  editUserForm['expiry_date'].value = user.expiry_date || '';
  editUserForm['is_admin'].checked  = user.is_admin;
  editUserForm['remarks'].value     = user.remarks || '';
  editUserModal.show();
}

editUserForm.addEventListener('submit', async e => {
  e.preventDefault();
  const data = {
    expiry_date: editUserForm['expiry_date'].value,
    is_admin:    editUserForm['is_admin'].checked,
    remarks:     editUserForm['remarks'].value.trim()
  };

  try {
    const res = await fetch(`/api/users/${currentEditUserId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
    const text = await res.text();
    let payload;
    try { payload = JSON.parse(text); } catch { throw new Error(text); }
    if (!res.ok) throw new Error(payload.error || payload.message || text);

    editUserModal.hide();
    await loadUserList();
  } catch (err) {
    alert('更新失败：' + err.message);
    console.error('Edit user error:', err);
  }
});

// ---------------------------------------
// 5. 删除用户功能
// ---------------------------------------
async function deleteUser(userId) {
  if (!confirm('确认要删除该用户吗？')) return;
  try {
    const res = await fetch(`/api/users/${userId}`, {
      method: 'DELETE'
    });
    const text = await res.text();
    let payload;
    try { payload = JSON.parse(text); } catch { /* ignore */ }
    if (!res.ok) throw new Error(payload?.error || payload?.message || text);

    await loadUserList();
  } catch (err) {
    alert('删除失败：' + err.message);
    console.error('Delete user error:', err);
  }
}

// ---------------------------------------
// 页面初次加载时拉取列表
// ---------------------------------------
document.getElementById('userMgmtModal')
  .addEventListener('show.bs.modal', () => {
    loadUserList();
  });

// 1. showDeleteConfirm：点击“删除”图标时调用
function deleteUser(userId) {
  currentDeleteUserId = userId;
  // 重置按钮状态
  deleteConfirmBtn.disabled = true;
  let countdown = 5;
  deleteConfirmBtn.textContent = `确认（${countdown}s）`;

  // 打开 Modal
  confirmDeleteModal.show();

  // 启动倒计时
  const timer = setInterval(() => {
    countdown -= 1;
    if (countdown > 0) {
      deleteConfirmBtn.textContent = `确认（${countdown}s）`;
    } else {
      clearInterval(timer);
      deleteConfirmBtn.textContent = '确认';
      deleteConfirmBtn.disabled = false;
    }
  }, 1000);
}

// 2. 绑定“确认”按钮的点击事件，真正执行删除
deleteConfirmBtn.addEventListener('click', async () => {
  if (!currentDeleteUserId) return;
  try {
    const res = await fetch(`/api/users/${currentDeleteUserId}`, { method: 'DELETE' });
    const text = await res.text();
    let payload;
    try { payload = JSON.parse(text); } catch { /* ignore */ }
    if (!res.ok) throw new Error(payload?.error || payload?.message || text);

    confirmDeleteModal.hide();
    await loadUserList();
  } catch (err) {
    alert('删除失败：' + err.message);
    console.error('Delete user error:', err);
  } finally {
    currentDeleteUserId = null;
  }
});